<html>
<head>
<style type="text/css">

table{	
border-collapse:collapse;	
}
tr.tables
{
border:1px solid darkgrey;
background-color:black;
color:white;
}

tr.attributes
{
border:1px solid white;
background-color:#303030;
color:white;
}
tr.rowa
{
border:1px solid white;
background-color:#D0D0D0;
color:black;
}
tr.rowb
{
border:1px solid white;
background-color:white;
color:black;
}
</style>
</head>
<body>

<?php

print "<form action=query.php method=post>";
print "Type an SQL Command into the following box. <br>";
print "<textarea rows='10' cols='100' name='command'>" . $_POST["command"] . "</textarea><br>";
print "<input type=radio name=db value=TEST /> TEST";
print "<input type=radio name=db value=CS143 checked=checked /> CS143 ";
print "<input type=submit  value=Run></form><br>";

$resTable= "Nothing";
$raw_command=$_POST["command"];
$DB=$_POST["db"];
//Open a connection to the server for a database.
$db_connection = mysql_connect("localhost", "cs143", "");
if(!$db_connection) {
    $errmsg = mysql_error($db_connection);
    print "Connection failed: " .$errmsg ."<br />";
    exit(1);
}
$command = $raw_command;
//$sanitized_command = mysql_real_escape_string($raw_command, $db_connection);

//If command is empty
if($command==""){
	exit(0);
}
//ensure
$pattern="/\w*(SELECT|SHOW).*/i";
if(!preg_match($pattern,$command)){
	print "Sorry! Only supports SELECT and SHOW!";
	exit(1);
}


//select the database to use.
mysql_select_db("$DB", $db_connection);
//issue query
$resTable = mysql_query($command, $db_connection);
if(!$resTable) {
    $errmsg = mysql_error($db_connection);

    if($command != ""){
    	print "Query fetch failed: " .$errmsg ."<br />";
    }

    exit(1);
}


//close the database when done
mysql_close($db_connection);
print "<h3>Database Table</h3>";
print "<table border=1 cellpadding=5>";
//get the first row
print "<tr class=tables>";
$currTable=NULL;
for ($i = 0; $i < mysql_num_fields($resTable); ++$i) {
    $table = mysql_field_table($resTable, $i);
    if($table != $currTable || $i ==  mysql_num_fields($resTable)-1 ){
		
		if($i ==  mysql_num_fields($resTable)-1)
			$colSpan=$colSpan+1;
		
		if($currTable != NULL){
			print  "<th colSpan=$colSpan><b>$currTable</b></th>";
		}
		$currTable=$table;
		$colSpan=1;
			
	}
	else{
		$colSpan=$colSpan+1;	
	}
}


print "</tr>";
print "<tr class=attributes>";
for ($i = 0; $i < mysql_num_fields($resTable); ++$i) {
    $field = mysql_field_name($resTable, $i);
    print  "<th ><b><i>$field</i></b></th>";
}
print "</tr>";

$rowcol=true;
while($row = mysql_fetch_row($resTable)){
	if($rowcol == true){
		print "<tr class=rowa>";
	}
	else{
		print "<tr class=rowb>";
	}
	$rowcol = !$rowcol;
    for($i=0; $i < sizeof($row); $i=$i+1){
			if($row[$i] == null)
				print "<td>N/A</td>";
			else
				print "<td>".$row[$i]."</td>";
		
	}
	print "</tr>";
};
print "</table>"



?>
<br>
</body>
</html>
